import requests

def get_request(url, headers=None, params=None):
    """
    发送 GET 请求

    参数:
    - url (str): 请求的 URL
    - headers (dict, optional): 请求头
    - params (dict, optional): URL 参数

    返回:
    - response: requests.Response 对象
    """
    try:
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()  # 检查 HTTP 错误
        return response
    except requests.exceptions.RequestException as e:
        print(f"GET 请求错误: {e}")
        return None

def post_request(url, headers=None, data=None, json=None):
    """
    发送 POST 请求

    参数:
    - url (str): 请求的 URL
    - headers (dict, optional): 请求头
    - data (dict, optional): 表单数据
    - json (dict, optional): JSON 数据

    返回:
    - response: requests.Response 对象
    """
    try:
        response = requests.post(url, headers=headers, data=data, json=json, verify=False)
        print('post_request response : ', response)
        response.raise_for_status()  # 检查 HTTP 错误
        return response
    except requests.exceptions.RequestException as e:
        print(f"POST 请求错误: {e}")
        return None


def download_file(url, filename):
    try:
        # 发送HTTP GET请求
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 打开文件进行写入
        with open(filename, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192): 
                # 如果有数据则写入文件
                if chunk:
                    f.write(chunk)
        print(f"文件已下载并保存为：{filename}")
        return True
    except requests.exceptions.HTTPError as errh:
        print(f"HTTP错误：{errh}")
        return False
    except requests.exceptions.ConnectionError as errc:
        print(f"连接错误：{errc}")
        return False
    except requests.exceptions.Timeout as errt:
        print(f"超时错误：{errt}")
        return False
    except requests.exceptions.RequestException as err:
        print(f"请求错误：{err}")
        return False